package com.apes.framework.plugin.esb.processor.connector.oap;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.esb.api.Request;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import com.apes.framework.util.Tools;
import com.apes.oap.RopRequestContext;
import com.apes.oap.RopUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：签名
 *
 * @author xul
 * @create 2019-10-23 11:57
 */
public class SignProcessor<T extends SimpleRequest, R> extends AbstractChainProcessor<T, R> {

    private String appKey;
    private String secret;
    private String method;
    private String version = "1.0";
    private String parse = "false";

    @Override
    protected R doProcess(T request) {
        JSONObject temp = request.getJO();

        RopRequestContext context = request.getRopRequestContext();
        if (StringUtils.isEmpty(method)) method = context.getMethod();
        Object o = request.getData();
        String body = o instanceof String ? (String) o : JSONObject.toJSONString(o);
        Map params = new HashMap();
        params.put("appKey", appKey);
        params.put("method", method);
        params.put("version", version);
        params.put("body", body);

        if ( parse.equals("true") && temp.containsKey("headers") && temp.containsKey("body")) {
            Map headers = temp.getJSONObject("headers");
            params.put("method", headers.get("method"));
            params.put("body", JSONObject.toJSONString(temp.get("body")));
        }

        String sessionId = context.getSessionId();
        if (!StringUtils.isEmpty(sessionId)) params.put("sessionId", sessionId);
        String signValue = RopUtils.sign(params, secret);
        params.put("sign", signValue);
        return (R) params;
    }

    public String getAppKey() {
        return appKey;
    }

    public void setAppKey(String appKey) {
        try {
            this.appKey = Tools.replace(appKey);
        } catch (Exception e) {
            this.appKey = appKey;
            e.printStackTrace();
        }
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        try {
            this.secret = Tools.replace(secret);
        } catch (Exception e) {
            this.secret = secret;
            e.printStackTrace();
        }
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getParse() {
        return parse;
    }

    public void setParse(String parse) {
        this.parse = parse;
    }
}
